package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.GroupDto;
import com.lanjiu.lib.imclient.dto.GroupVo;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSRequester;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.CollectionUtils;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.AvatarHorizontalAdapter;
import com.ljkj.cordial.chat.adapter.PersonnelAdapter;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.AlbumTableBean;
import com.ljkj.cordial.chat.dao.UserTableBean;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.InviteFriendView;
import com.ljkj.cordial.chat.util.AlbumManageUtil;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.nic.view.adapter.CommonCheckAdapter;
import com.nic.view.model.CheckType;
import com.nic.view.util.JToast;
import com.nic.view.util.contactList.PinyinListView;
import com.nic.view.widget.ContainsEmojiEditText;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 邀请好友
 */
public class InviteFriendActivity extends AppEventActivity<InviteFriendView> implements CommonCheckAdapter.OnClickItemMultiListener, AvatarHorizontalAdapter.OnImageClickListener {


    @BindView(R.id.listView)
    PinyinListView listView;
    @BindView(R.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R.id.search_edit)
    ContainsEmojiEditText mSearchBox;

    private AvatarHorizontalAdapter avatarHorizontalAdapter;

    private String checkedIds;
    private PersonnelAdapter personnelAdapter;
    private int membType;
    private String mGroupId;
    private String mGroupName;
    private String mMemberId;

    private List<FriendTable> mDataSet;

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_invite_friend;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        membType = getIntent().getIntExtra(Canstants.KEY_MEMBER_INVITE_TYPE, Canstants.MEMBER_STATE_ADD);
        mGroupId = getIntent().getStringExtra(Canstants.EXTRA_KEY_GROUP_ID);
        mGroupName = getIntent().getStringExtra(Canstants.EXTRA_KEY_GROUP_NAME);
        mMemberId = getIntent().getStringExtra(Canstants.KEY_CHAT_TARGET_MEMBER);

        getToolbarRightTv().setVisibility(View.VISIBLE);


        getToolbarRightTv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(checkedIds)) {
                    return;
                }
                if (Canstants.MEMBER_STATE_ADD == membType) {   // 邀请
                    obtainView().doInviteGroup(mGroupId, checkedIds);
                } else if (Canstants.MEMBER_STATE_CREATE == membType) {   // 创建
                    obtainView().doCreateGroup(checkedIds);
                } else {    // 删除
                    showNet(isShowDefNetDialog());
                    obtainView().doDeleteGroup(mGroupId, mGroupName, personnelAdapter.getCheckedList(), mMemberId);
                }

//                Intent intent = new Intent();
//                intent.putExtra(Canstants.KEY_GROUP_INVITE, checkedIds);
//                if (Canstants.MEMBER_STATE_ADD == membType) {
//                    intent.putExtra(Canstants.KEY_MEMBER_INVITE_TYPE, Canstants.MEMBER_STATE_ADD);
//                } else {
//                    intent.putExtra(Canstants.KEY_MEMBER_INVITE_TYPE, Canstants.MEMBER_STATE_REMOVE);
//                }
//                setResult(Canstants.KEY_GROUP_INVITE_RESULT, intent);
//                finish();
            }
        });
        recycleView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recycleView.setItemAnimator(new DefaultItemAnimator());
        avatarHorizontalAdapter = new AvatarHorizontalAdapter(this);
        recycleView.setAdapter(avatarHorizontalAdapter);
        avatarHorizontalAdapter.setOnImageClickListener(this);
        personnelAdapter = new PersonnelAdapter(CheckType.MULTI);
        personnelAdapter.setOnItemClickListener(new PersonnelAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, Object obj, int position) {
                if (CheckType.NONE.equals(personnelAdapter.getCheckType())) {
                    FriendTable item = (FriendTable) obj;
                    FriendInfoActivity.jumpTo(view.getContext(), IMSContacts.UserType.REGISTERED_USER.equals(item.getUserType()) ? Canstants.KEY_REGISTER : Canstants.KEY_VISITOR, item.getFriendNickname(), item.getFriendUserId(), item.getUserType());
                }
            }
        });
        listView.getListView().setAdapter(personnelAdapter);
        listView.setSideBarVisibility(View.GONE);
        personnelAdapter.setClickItemMultiListener(this);
        mDataSet = new ArrayList<>();
        if (Canstants.MEMBER_STATE_ADD == membType) {
            getToolbar().setTitle("邀请好友");
            getToolbarRightTv().setText("邀请");
            setNotInGroupMemberData();
        } else if (Canstants.MEMBER_STATE_CREATE == membType) {
            getToolbar().setTitle("邀请好友");
            getToolbarRightTv().setText("创建");
            mDataSet.clear();
            mDataSet.addAll(getUserInfors());
            setData(mDataSet);
        } else {
            getToolbar().setTitle("删除群成员");
            getToolbarRightTv().setText("删除");
            setNotMeGroupMemberData();
        }
        getToolbarRightTv().setEnabled(false);
        getToolbarRightTv().setTextColor(ContextCompat.getColor(this, R.color.disabled));

        mSearchBox.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!CollectionUtils.isEmpty(mDataSet)) {
                    if (TextUtils.isEmpty(s.toString())) {
                        setData(mDataSet);
                    } else {
                        setData(search(s.toString()));
                    }
                }
            }
        });
    }

    public static void jumpToCreate(Activity activity) {
        Intent intent = new Intent(activity, InviteFriendActivity.class);
        intent.putExtra(Canstants.KEY_MEMBER_INVITE_TYPE, Canstants.MEMBER_STATE_CREATE);
        activity.startActivityForResult(intent, Canstants.KEY_GROUP_INVITE_RESULT);
    }

    public static void jumpToInvite(Activity activity, String groupId) {
        Intent intent = new Intent(activity, InviteFriendActivity.class);
        intent.putExtra(Canstants.KEY_MEMBER_INVITE_TYPE, Canstants.MEMBER_STATE_ADD);
        intent.putExtra(Canstants.EXTRA_KEY_GROUP_ID, groupId);
        activity.startActivityForResult(intent, Canstants.KEY_GROUP_INVITE_RESULT);
    }

    public static void jumpToDelete(Activity activity, String groupId, String groupName, String memberId) {
        Intent intent = new Intent(activity, InviteFriendActivity.class);
        intent.putExtra(Canstants.KEY_MEMBER_INVITE_TYPE, Canstants.MEMBER_STATE_REMOVE);
        intent.putExtra(Canstants.EXTRA_KEY_GROUP_ID, groupId);
        intent.putExtra(Canstants.EXTRA_KEY_GROUP_NAME, groupName);
        intent.putExtra(Canstants.KEY_CHAT_TARGET_MEMBER, memberId);
        activity.startActivityForResult(intent, Canstants.KEY_GROUP_INVITE_RESULT);
    }

    public void setData(List<FriendTable> data) {
        personnelAdapter.clear();
        List<FriendTable> userInfors = new ArrayList<>(data);
        Executors.newSingleThreadScheduledExecutor().schedule(() -> PinyinListView.insertTitle(userInfors, new PinyinListView.PinyinFactory<FriendTable>() {

            @Override
            public FriendTable create() {
                return new FriendTable();
            }

            @Override
            public void finish(final List<FriendTable> t) {
                if (!isFinishing()) {
                    runOnUiThread(() -> personnelAdapter.setList(t));
                }
            }
        }), 0, TimeUnit.SECONDS);
    }

    private List<FriendTable> getUserInfors() {
        return FriendTable.query();
    }

    private void setNotInGroupMemberData() {
        ObserverThread.create().onNextThread2(new ObserverThread.OnListActionListener<FriendTable>() {
            @Override
            public void onAction(List<FriendTable> list) {
                mDataSet.clear();
                mDataSet.addAll(list);
                setData(mDataSet);
            }

            @Override
            public List<FriendTable> onThreadAction() {
                List<GroupMemberTable> query = GroupMemberTable.query(mGroupId);

                List<String> ids = new ArrayList<>();
                for (GroupMemberTable table : query) {
                    ids.add(table.getGroupMemberUserId());
                }
                return FriendTable.queryNotInGroup(ids);
            }
        });
    }

    private void setNotMeGroupMemberData() {
        ObserverThread.create().onNextThread2(new ObserverThread.OnListActionListener<FriendTable>() {
            @Override
            public void onAction(List<FriendTable> list) {
                mDataSet.clear();
                mDataSet.addAll(list);
                setData(mDataSet);
            }

            @Override
            public List<FriendTable> onThreadAction() {
                List<GroupMemberTable> query = GroupMemberTable.query(mGroupId);
                List<FriendTable> set = new ArrayList<>();
                for (GroupMemberTable groupMemberTable : query) {
                    if (groupMemberTable.getGroupMemberUserId().equals(ChatApp.getInstance().getUserId())) {
                        continue;
                    }
                    FriendTable tableByFriendUserId = FriendTable.getTableByFriendUserId(groupMemberTable.getGroupMemberUserId());
                    if (null != tableByFriendUserId) {
                        FriendTable f = new FriendTable();
                        f.setFriendUserId(tableByFriendUserId.getFriendUserId());
                        f.setFriendNickname(tableByFriendUserId.getFriendNickname());
                        f.setFriendAvatar(tableByFriendUserId.getFriendAvatar());
                        f.setFriendAvatarId(tableByFriendUserId.getFriendAvatarId());
                        f.setFriendAvatarPath(tableByFriendUserId.getFriendAvatarPath());
                        f.setFriendAlias(tableByFriendUserId.getFriendAlias());
                        f.setUserType(tableByFriendUserId.getUserType());
                        f.setLoginUserId(UserPreferences.getUserId());
                        set.add(f);
                    } else {
                        FriendTable f = new FriendTable();
                        f.setFriendUserId(groupMemberTable.getGroupMemberUserId());
                        f.setFriendNickname(groupMemberTable.getGroupMemberName());
                        f.setFriendAvatar(groupMemberTable.getGroupMemberAvatar());
                        f.setFriendAvatarId(groupMemberTable.getGroupMemberAvatarId());
                        f.setFriendAvatarPath(groupMemberTable.getGroupMemberAvatarPath());
                        f.setFriendAlias(groupMemberTable.getGroupMemberAlias());
                        f.setUserType(groupMemberTable.getUserType());
                        f.setLoginUserId(UserPreferences.getUserId());
                        set.add(f);
                    }
                }
                return set;
            }
        });
    }

    @Override
    public void checkedItem(Map<String, String> map) {
        checkedIds = TextUtils.join(",", map.keySet());
        if (Canstants.MEMBER_STATE_ADD == membType) {
            getToolbarRightTv().setEnabled(map.size() > 0);
            getToolbarRightTv().setTextColor(ContextCompat.getColor(this, map.size() > 0 ? R.color.white : R.color.disabled));
            getToolbarRightTv().setText(String.format("邀请(%d)", map.size()));
        } else if (Canstants.MEMBER_STATE_CREATE == membType) {
            getToolbarRightTv().setText(String.format("创建(%d)", map.size()));
            if (map.size() > 1) {
                getToolbarRightTv().setEnabled(true);
                getToolbarRightTv().setTextColor(ContextCompat.getColor(this, R.color.white));
            } else {
                getToolbarRightTv().setEnabled(false);
                getToolbarRightTv().setTextColor(ContextCompat.getColor(this, R.color.disabled));
            }
        } else {
            getToolbarRightTv().setEnabled(map.size() > 0);
            getToolbarRightTv().setTextColor(ContextCompat.getColor(this, map.size() > 0 ? R.color.white : R.color.disabled));
            getToolbarRightTv().setText(String.format("删除(%d)", map.size()));
        }
        avatarHorizontalAdapter.setUrlList(personnelAdapter.getCheckedList());
    }


    @Override
    protected InviteFriendView bindNettyMessageView() {
        return new InviteFriendView(new InviteFriendView.InviteFriendCallback() {
            @Override
            public void onCreateGroupCallback(int code, String msg, GroupDto data) {
                if (code == IMSContacts.ResponseCode.SUCCESS && data != null) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                        @Override
                        public void onAction(Object obj) {
                            finish();
                        }

                        @Override
                        public Object onThreadAction() {
                            GroupTable table = GroupTable.queryRowByGroupIdNotNull(String.valueOf(data.getGroupId()));
//                            table.setGroupOwnerId(data.getOwner());
                            table.setGroupId(data.getGroupId());
                            table.setGroupName(data.getGroupName());
                            table.setGroupType(IMSUtils.userTypeAnalysis(data.getGroupId()));
//                            table.setAnnouncementContent(data.getAnnouncement());
//                            table.setMemberCount(data.getAmount());
                            GroupTable.insert(table);
                            IMSRequester.requestGroupMemberListDontSayHi(data.getGroupId());
//                            if (!CollectionUtils.isEmpty(data.getGroupMembers())) {
//                                List<GroupVo.GroupMemberVo> groupMembers = data.getGroupMembers();
//                                for (GroupVo.GroupMemberVo groupMember : groupMembers) {
//                                    GroupMemberTable mTable = GroupMemberTable.create(String.valueOf(data.getGroupId()), groupMember.getMemberUserId());
//                                    mTable.setGroupId(table.getGroupId());
//                                    mTable.setGroupMemberId(String.valueOf(groupMember.getGroupMemberId()));
//                                    mTable.setGroupMemberAvatar(groupMember.getMemberUserPhoto());
//                                    mTable.setGroupMemberUserId(groupMember.getMemberUserId());
//                                    mTable.setGroupMemberName(groupMember.getMemberNickname());
//                                    if (groupMember.getMemberUserId().equals(data.getOwner()))
//                                        mTable.setGroupMemberType(1);
//                                    else
//                                        mTable.setGroupMemberType(0);
//                                    mTable.setUserType(groupMember.getMemberUserType());
//                                    GroupMemberTable.insertOrUpdate(mTable);
//                                }
//                            }
                            return "";
                        }
                    });
                } else {
                    if (TextUtils.isEmpty(msg)) msg = "群创建失败！";
                    JToast.showShort(InviteFriendActivity.this, msg);
                }
            }

            @Override
            public void onInviteGroupCallback(int code, String msg) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                        @Override
                        public void onAction(Object obj) {
                            MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.GROUP_MEMBER_COUNT_REFRESH);
                            event.setData("-");
                            EventBus.getDefault().post(event);
                            setResult(Canstants.KEY_GROUP_INVITE_RESULT);
                            finish();
                        }

                        @Override
                        public Object onThreadAction() {
                            List<FriendTable> checkedList = personnelAdapter.getCheckedList();
                            for (FriendTable table : checkedList) {
                                GroupMemberTable mTable = GroupMemberTable.create(mGroupId, table.getFriendUserId());
                                mTable.setGroupId(mGroupId);
                                mTable.setGroupMemberAvatar(table.getFriendAvatar());
                                mTable.setGroupMemberAvatarId(table.getFriendAvatarId());
                                mTable.setGroupMemberAvatarPath(table.getFriendAvatarPath());
                                mTable.setGroupMemberUserId(table.getFriendUserId());
                                mTable.setGroupMemberName(table.getFriendNickname());
                                mTable.setGroupMemberAlias(table.getFriendAlias());
                                mTable.setGroupMemberType(0);
                                mTable.setUserType(IMSUtils.userTypeAnalysis(table.getFriendUserId()));
                                if (GroupMemberTable.insertOrUpdate(mTable) > 0) {
                                    GroupTable.addMemberCount(mGroupId);
                                }
                            }
                            return null;
                        }
                    });
                } else {
                    if (TextUtils.isEmpty(msg)) msg = "邀请发送失败！";
                    JToast.showShort(InviteFriendActivity.this, msg);
                }
            }

            @Override
            public void onDeleteGroupCallback(int code, String msg) {
                if (code == IMSContacts.ResponseCode.SUCCESS) {
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                        @Override
                        public void onAction(Object obj) {
                            setResult(Canstants.KEY_GROUP_INVITE_RESULT);
                            finish();
                        }

                        @Override
                        public Object onThreadAction() {
                            if (!TextUtils.isEmpty(checkedIds)) {
                                String[] userIds = checkedIds.split(",");
                                for (String userId : userIds) {
                                    try {
                                        if (GroupMemberTable.deleteByUserId(mGroupId, userId)) {
                                            GroupTable.subMemberCount(mGroupId);
                                        }
                                    } catch (Exception e) {
                                        System.err.println(e.getLocalizedMessage());
                                    }
                                }
                            }
                            return "";
                        }
                    });
                } else {
                    if (TextUtils.isEmpty(msg)) msg = "删除失败！";
                    JToast.showShort(InviteFriendActivity.this, msg);
                }
            }
        });
    }

    @Override
    public void onClick(View v, FriendTable item, int position) {

    }

    private List<FriendTable> search(String keyword) {
        List<FriendTable> searchResult = new ArrayList<>();
        for (FriendTable table : mDataSet) {
            if (!TextUtils.isEmpty(table.getFriendAlias())) {
                if (table.getFriendAlias().contains(keyword)) {
                    searchResult.add(table);
                }
                continue;
            }
            if (!TextUtils.isEmpty(table.getFriendNickname())) {
                if (table.getFriendNickname().contains(keyword)) {
                    searchResult.add(table);
                }
            }
        }
        return searchResult;
    }
}
